package www.ld.com.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import www.ld.com.common.CacheKeyConstants;
import www.ld.com.domain.category.pojo.CategoryPO;
import www.ld.com.domain.vo.SelectTreeVO;
import www.ld.com.mapper.CategoryMapper;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryCacheService {
    @Resource
    private CategoryMapper cateGoryMapper;

    @Cacheable(value = CacheKeyConstants.CategoryKey.CACHE_NAME, key = "'"+CacheKeyConstants.CategoryKey.KEY_FIND_ALL+"'")
    public List<SelectTreeVO> findAll() {
        final List<CategoryPO> categoryPOS = cateGoryMapper.selectList(new LambdaQueryWrapper<CategoryPO>().orderByAsc(CategoryPO::getId));
        final List<SelectTreeVO> collect = categoryPOS.stream().map(v -> {
            return BeanUtil.toBean(v, SelectTreeVO.class);
        }).collect(Collectors.toList());
        return Collections.unmodifiableList(collect);
    }

    @Cacheable(value = CacheKeyConstants.CategoryKey.CACHE_NAME,key = "'"+ CacheKeyConstants.CategoryKey.KEY_GET_CATEGORY_NAME_BY_ID +"'+#p0")
    public String getCategoryNameById(@NotNull String id) {
        if("0".equals(id)){
            return null;
        }
        CategoryPO categoryPO = cateGoryMapper.selectById(id);
        return ObjectUtil.isNull(categoryPO) ? "" : categoryPO.getName();
    }
}
